﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using LabChecker.Models;
using System.IO;
using System.Xml.Linq;

namespace LabChecker.Services
{
    public static class SubjectImportService
    {
        public static Subject Import(Stream InputStream)
        {
            IList<string> errors = new List<string>();
            var deserializedSubject = new Subject();
            
            var subjectDocument = XDocument.Load(new StreamReader(InputStream));            
            var subjectElement = subjectDocument.Element("{http://checker.org/Subject}subject");
            deserializedSubject.Name = (string)subjectElement.Element("{http://checker.org/Subject}name");
            var tasksElement = subjectElement.Element("{http://checker.org/Subject}tasks");
            foreach (var taskElement in tasksElement.Elements("{http://checker.org/Subject}task"))
            {
                deserializedSubject.Tasks.Add(GetTaskFromTaskElement(taskElement));
            }
            return deserializedSubject;
        }

        private static Task GetTaskFromTaskElement(XElement taskElement)
        {
            var index = 0;
            var task = new Task();
            var descriptionElement = taskElement.Element("{http://checker.org/Subject}description");
            task.Description.Title = (string)descriptionElement.Element("{http://checker.org/Subject}title");
            task.Description.Problem = (string)descriptionElement.Element("{http://checker.org/Subject}problem");
            task.Description.Input = (string)descriptionElement.Element("{http://checker.org/Subject}input");
            task.Description.Output = (string)descriptionElement.Element("{http://checker.org/Subject}output");
            var dataElement = taskElement.Element("{http://checker.org/Subject}data");
            foreach (var testCaseElement in dataElement.Descendants("{http://checker.org/Subject}testCase"))
            {
                var deserializedTestCase = new TestCase();
                deserializedTestCase.Index = index++;
                deserializedTestCase.Input = (string)testCaseElement.Element("{http://checker.org/Subject}input");
                deserializedTestCase.Answer = (string)testCaseElement.Element("{http://checker.org/Subject}answer");
                var messageElement = testCaseElement.Element("{http://checker.org/Subject}message");
                deserializedTestCase.ErrorMessage = messageElement != null ? (string)messageElement : null;
                deserializedTestCase.IsExample = (bool?)testCaseElement.Attribute("isExample") ?? false;
                task.TestCases.Add(deserializedTestCase);
            }
            return task;
        }
    }
}